#定时完成task
from .models import User, Movie, Rating
import copy


#从数据库提取每个种类电影高分最多的电影的id号保存到文件中，并且保存每个种类评分最高的电影id到All_top
def top_rating():
    movies = Movie.objects.all()
    genre_list = ['Action', 'Adventure', 'Animation', 'Childrens', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy',
                  'Film-Noir', 'Horror', 'Musical', 'Mystery', 'Romance', 'Sci-Fi',
                  'Thriller', 'War', 'Western']
    genre_idx_dict = {i: genre for i, genre in zip(range(len(genre_list)), genre_list)}
    genre_dict = {
        genre: [] for genre in genre_list
    }

    rating_dict = copy.deepcopy(genre_dict)
    for movie in movies:
        genres = list(movie.genre)
        for i, genre in zip(range(len(genres)), genres):
            if genre == '1':
                genre_dict[genre_idx_dict[i]].append(movie)
    file_all = open('top/All_top', 'w')
    for genre in genre_dict:
        for movie in genre_dict[genre]:
            ratings = Rating.objects.filter(movie_id=movie.id, rating=5)
            rating_dict[genre].append([movie.id, len(ratings)])
        rating_dict[genre] = sorted(rating_dict[genre], key=lambda x: x[1], reverse=True)
        # rating_dict[genre] = rating_dict[genre][0:10] #去top10
        with open('top/' + genre + '_top', 'w') as f:
            for top in rating_dict[genre]:
                f.write(str(top[0]) + '\n')
        file_all.write(str(rating_dict[genre][0][0]) + '\n')
    file_all.close()


